package com.ayoka.http;

import android.app.Activity;
import android.text.TextUtils;

import com.ayoka.R;
import com.ayoka.base.AppContext;
import com.ayoka.bean.BaseResponse;
import com.ayoka.bean.ResponseRefreshTokenBean;
import com.ayoka.bean.UserInformation;
import com.ayoka.Constant;
import com.jcp.baselibrary.base.APPActivityManager;
import com.jcp.baselibrary.okhttp3.OkHttpUtil;
import com.jcp.baselibrary.okhttp3.response.OkHttpResBeanHandler;
import com.jcp.baselibrary.utils.MyLogger;
import com.jcp.baselibrary.utils.ToastUtil;
import com.jcp.baselibrary.utils.UIUtils;

import okhttp3.Headers;

/**
 * =========================================================
 * 作者： 金春平
 * 类名： OkHttpListener
 * 类描述：
 * 创建日期 17/09/04
 * =========================================================
 */
public abstract class OkHttpListener<T> extends OkHttpResBeanHandler<T> {

    public static final int CODE_PARSE_ERROR = 0x001;

    @Override
    public void onSuccess(int code, Headers headers, T response) {
        /**
         * 根据需要重新定制成功失败判断
         */
        if (response instanceof BaseResponse) {
            // 处理用户相关返回体
            BaseResponse baseResponse = (BaseResponse) response;
            if (0 == baseResponse.errcode) {
                onSuccess(response);
            } else {
                onFailure(baseResponse.errcode, baseResponse.errmsg);
            }
        } else {
            onFailure(CODE_PARSE_ERROR, "请求类型错误！");
        }
    }

    public abstract void onSuccess(T response);

    public abstract void onFailure(int errorCode, String errorMessage);

    @Override
    public void onFailure(int errorCode, Headers headers, int error, Throwable t) {
        MyLogger.e("errorCode = " + errorCode);
        t.printStackTrace();
        if (errorCode == Constant.WX_ERROR_CODE){
            refreshToken();
            return;
        }
        if (errorCode == Constant.WX_ERROR_TOKEN){
            reLogin();
            return;
        }
        if (error == RESPONSE_ERROR_SERVER) {
            onFailure(errorCode, UIUtils.getString(R.string.service_error));
        } else if (error == RESPONSE_ERROR_NET) {
            onFailure(errorCode, UIUtils.getString(R.string.network_error));
        } else {
            onFailure(errorCode, t != null ? t.getMessage() : UIUtils.getString(R.string.request_error));
        }
    }

    // 刷新Token
    public synchronized void refreshToken() {
        if (UserInformation.getInstance() == null || TextUtils.isEmpty(UserInformation.getInstance().refresh_token)){
            reLogin();
            return;
        }
        API.refreshToken(UserInformation.getInstance().user_info.ID, UserInformation.getInstance().refresh_token, new OkHttpListener<BaseResponse<ResponseRefreshTokenBean>>() {

            @Override
            public void onSuccess(BaseResponse<ResponseRefreshTokenBean> response) {
                ResponseRefreshTokenBean responseRefreshTokenBean = response.data;
                if (TextUtils.isEmpty(responseRefreshTokenBean.refresh_token) || TextUtils.isEmpty(responseRefreshTokenBean.session_token)) return;
                UserInformation.getInstance().refresh_token = responseRefreshTokenBean.refresh_token;
                UserInformation.getInstance().session_token = responseRefreshTokenBean.session_token;
                UserInformation.save();
                OkHttpUtil.restartRequest();
            }

            @Override
            public void onFailure(int code, String errorMessage) {
                reLogin();
            }
        });
    }

    // 需要重新登录
    private void reLogin(){
        UserInformation.setUserInformation(null);
        Activity currentActivity = APPActivityManager.getInstance().getTopActivity();
        if (currentActivity != null) {
            ToastUtil.getInstance().show("登录超时，请重新登录");
            AppContext.logout(currentActivity);
        }
    }
}
